package com.yang.sso.oauth.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *  解析token
 * @author: lslands
 * @version: v2.0
 * @create: 2022/2/16 13:29
 **/
public class ParsingToken {

    public static final String PUBLIC_KEY = "publicKey.key";

    /**
     * 获取非对称加密公钥
     * @return String
     */
    public static String getPublicKey(){
        Resource resource = new ClassPathResource(PUBLIC_KEY);
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(resource.getInputStream());
            BufferedReader br = new BufferedReader(inputStreamReader);

            return br.lines().collect(Collectors.joining("\n"));
        }catch (IOException e){
            return null;
        }
    }

    public static Object token(){
      try {
          RequestAttributes ra = RequestContextHolder.getRequestAttributes();
          ServletRequestAttributes sra = (ServletRequestAttributes) ra;
          HttpServletRequest request =sra.getRequest();
          String authorization = request.getHeader("Authorization");
          String token =  authorization.replace("Bearer ","");
          Jwt jwt  = JwtHelper.decodeAndVerify(token, new RsaVerifier(getPublicKey()));
          String claims = jwt.getClaims();
          Object userData = JSONObject.parseObject(JSONObject.toJSONString(JSON.parseObject(claims, Map.class), true), Object.class);
          return userData;
      }catch (Exception  e){
          e.printStackTrace();
      }
      return null;
    }
}
